Class spinitron\dynamicAr\DynamicActiveRecord

Inheritancespinitron\dynamicAr\DynamicActiveRecord » yii\db\ActiveRecord » yii\db\BaseActiveRecord » yii\base\Model » yii\base\Component » yii\base\Object
ImplementsArrayAccess, IteratorAggregate, yii\base\Arrayable, yii\base\Configurable, yii\db\ActiveRecordInterface
Uses Traitsyii\base\ArrayableTrait
Subclassesexamples\shop\Product, tests\unit\data\BaseRecord, tests\unit\data\ar\Category, tests\unit\data\ar\Customer, tests\unit\data\ar\Item, tests\unit\data\ar\NullValues, tests\unit\data\ar\Order, tests\unit\data\ar\OrderItem, tests\unit\data\ar\OrderItemWithNullFK, tests\unit\data\ar\OrderWithNullFK, tests\unit\data\ar\Profile, tests\unit\data\ar\Type, tests\unit\data\dar\MissingDynColumn, tests\unit\data\dar\Person, tests\unit\data\dar\Product, tests\unit\data\dar\Supplier

DynamicActiveRecord represents relational data with structured dynamic attributes in addition to column attributes supported by ActiveRecord.

DynamicActiveRecord adds structured dynamic attributes to Yii 2 ActiveRecord a bit like adding a document, in the sense of a NoSQL document store database, to each SQL table record. At present this is implemented for Maria 10.0+ Dynamic Columns.

You can read and write attributes of a DynamicActiveRecord model that are not instance variables, column attributes or virtual attribute. In other words, you can make up attribute names on-the-fly, assign values and they are stored in the database. You can then involve these dynamic attributes in queries using spinitron\dynamicAr\DynamicActiveQuery.

Dynamic attributes may also be data structures in the form of PHP arrays, elements of which can be accessed through dotted attribute notation.

$model->specs = ['dimensions' => ['length' => 20]];
$model->setAttribute('specs.dimensions.width', 4);
$model->setAttribute('specs.color', 'blue');
// $model->specs now has the value
// ['dimensions' => ['length' => 20, 'width' => 4], 'color' => 'blue']

Model classes must implement the dynamicColumn() method to specify the name of the table column containing the serialized dynamic attributes.

Public Properties

Hide inherited properties

PropertyTypeDescriptionDefined By
$activeValidators \yii\validators\Validator[] The validators applicable to the current $scenario. yii\base\Model
$attributes array Attribute values (name => value). yii\base\Model
$behaviors \yii\base\Behavior[] List of behaviors attached to this component yii\base\Component
$dirtyAttributes array The changed attribute values (name-value pairs) yii\db\BaseActiveRecord
$errors array Errors for all attributes or the specified attribute. yii\base\Model
$firstErrors array The first errors. yii\base\Model
$isNewRecord boolean Whether the record is new and should be inserted when calling save(). yii\db\BaseActiveRecord
$iterator ArrayIterator An iterator for traversing the items in the list. yii\base\Model
$oldAttributes array The old attribute values (name-value pairs) yii\db\BaseActiveRecord
$oldPrimaryKey mixed The old primary key value. yii\db\BaseActiveRecord
$primaryKey mixed The primary key value. yii\db\BaseActiveRecord
$relatedRecords array An array of related records indexed by relation names. yii\db\BaseActiveRecord
$scenario string The scenario that this model is in. yii\base\Model
$validators ArrayObject|\yii\validators\Validator[] All the validators declared in the model. yii\base\Model

Protected Properties

Hide inherited properties

PropertyTypeDescriptionDefined By
$placeholderCounter integer Counter of PDO placeholders used in a query. spinitron\dynamicAr\DynamicActiveRecord

Public Methods

Hide inherited methods

MethodDescriptionDefined By
__call() Calls the named method which is not a class method. yii\base\Component
__clone() This method is called after the object is created by cloning an existing one. yii\base\Component
__construct() Constructor. yii\base\Object
__get() PHP getter magic method. spinitron\dynamicAr\DynamicActiveRecord
__isset() Checks if a property value is null. spinitron\dynamicAr\DynamicActiveRecord
__set() PHP setter magic method. spinitron\dynamicAr\DynamicActiveRecord
__unset() Sets a component property to be null. spinitron\dynamicAr\DynamicActiveRecord
activeAttributes() Returns the attribute names that are subject to validation in the current scenario. yii\base\Model
addError() Adds a new error to the specified attribute. yii\base\Model
addErrors() Adds a list of errors. yii\base\Model
afterDelete() This method is invoked after deleting a record. yii\db\BaseActiveRecord
afterFind() This method is called when the AR object is created and populated with the query result. yii\db\BaseActiveRecord
afterSave() This method is called at the end of inserting or updating a record. yii\db\BaseActiveRecord
afterValidate() This method is invoked after validation ends. yii\base\Model
attachBehavior() Attaches a behavior to this component. yii\base\Component
attachBehaviors() Attaches a list of behaviors to the component. yii\base\Component
attributeHints() Returns the attribute hints. yii\base\Model
attributeLabels() Returns the attribute labels. yii\base\Model
attributes() Returns the list of attribute names. yii\base\Model
beforeDelete() This method is invoked before deleting a record. yii\db\BaseActiveRecord
beforeSave() spinitron\dynamicAr\DynamicActiveRecord
beforeValidate() This method is invoked before validation starts. yii\base\Model
behaviors() Returns a list of behaviors that this component should behave as. yii\base\Component
canGetProperty() Returns a value indicating whether a property can be read. yii\base\Component
canSetProperty() Returns a value indicating whether a property can be set. yii\base\Component
className() Returns the fully qualified name of this class. yii\base\Object
clearErrors() Removes errors for all attributes or a single attribute. yii\base\Model
columnExpression() Generate an SQL expression referring to the given dynamic column. spinitron\dynamicAr\DynamicActiveRecord
createValidators() Creates validator objects based on the validation rules specified in rules(). yii\base\Model
decodeForMaria() Decode strings encoded as data URIs. spinitron\dynamicAr\DynamicActiveRecord
delete() Deletes the table row corresponding to this active record. yii\db\ActiveRecord
deleteAll() Deletes rows in the table using the provided conditions. yii\db\ActiveRecord
detachBehavior() Detaches a behavior from the component. yii\base\Component
detachBehaviors() Detaches all behaviors from the component. yii\base\Component
dotAttributeNames() Return a list of all model attribute names recursing structured dynamic attributes. spinitron\dynamicAr\DynamicActiveRecord
dotAttributes() Return a list of all attribute values with keys in dotted notation. spinitron\dynamicAr\DynamicActiveRecord
dynColDecode() Decode a serialized blob of dynamic attributes. spinitron\dynamicAr\DynamicActiveRecord
dynColExpression() Creates a dynamic column SQL expression representing the given attributes. spinitron\dynamicAr\DynamicActiveRecord
dynamicColumn() Specifies the name of the table column containing dynamic attributes. spinitron\dynamicAr\DynamicActiveRecord
encodeForMaria() Encode as data URIs strings that JSON cannot express. spinitron\dynamicAr\DynamicActiveRecord
ensureBehaviors() Makes sure that the behaviors declared in behaviors() are attached to this component. yii\base\Component
equals() Returns a value indicating whether the given active record is the same as the current one. yii\db\ActiveRecord
extraFields() Returns the list of fields that can be expanded further and returned by toArray(). yii\base\ArrayableTrait
fields() Returns the list of fields that should be returned by default by toArray() when no specific fields are specified. spinitron\dynamicAr\DynamicActiveRecord
find() Returns a query object for the model/class. spinitron\dynamicAr\DynamicActiveRecord
findAll() Returns a list of active record models that match the specified primary key value(s) or a set of column values. yii\db\BaseActiveRecord
findBySql() Creates an yii\db\ActiveQuery instance with a given SQL statement. yii\db\ActiveRecord
findOne() Returns a single active record model instance by a primary key or an array of column values. yii\db\BaseActiveRecord
formName() Returns the form name that this model class should use. yii\base\Model
generateAttributeLabel() Generates a user friendly attribute label based on the give attribute name. yii\base\Model
getActiveValidators() Returns the validators applicable to the current $scenario. yii\base\Model
getAttribute() Returns a model attribute value. spinitron\dynamicAr\DynamicActiveRecord
getAttributeHint() Returns the text hint for the specified attribute. yii\base\Model
getAttributeLabel() Returns the text label for the specified attribute. yii\base\Model
getAttributes() Returns attribute values. yii\base\Model
getBehavior() Returns the named behavior object. yii\base\Component
getBehaviors() Returns all behaviors attached to this component. yii\base\Component
getDb() Returns the database connection used by this AR class. yii\db\ActiveRecord
getDirtyAttributes() Returns the attribute values that have been modified since they are loaded or saved most recently. yii\db\BaseActiveRecord
getErrors() Returns the errors for all attribute or a single attribute. yii\base\Model
getFirstError() Returns the first error of the specified attribute. yii\base\Model
getFirstErrors() Returns the first error of every attribute in the model. yii\base\Model
getIsNewRecord() Returns a value indicating whether the current record is new. yii\db\BaseActiveRecord
getIterator() Returns an iterator for traversing the attributes in the model. yii\base\Model
getOldAttribute() Returns the old value of the named attribute. yii\db\BaseActiveRecord
getOldAttributes() Returns the old attribute values. yii\db\BaseActiveRecord
getOldPrimaryKey() Returns the old primary key value(s). yii\db\BaseActiveRecord
getPrimaryKey() Returns the primary key value(s). yii\db\BaseActiveRecord
getRelatedRecords() Returns all populated related records. yii\db\BaseActiveRecord
getRelation() Returns the relation object with the specified name. yii\db\BaseActiveRecord
getScenario() Returns the scenario that this model is used in. yii\base\Model
getTableSchema() Returns the schema information of the DB table associated with this AR class. yii\db\ActiveRecord
getValidators() Returns all the validators declared in rules(). yii\base\Model
hasAttribute() Returns a value indicating whether the model has an attribute with the specified name. yii\db\BaseActiveRecord
hasErrors() Returns a value indicating whether there is any validation error. yii\base\Model
hasEventHandlers() Returns a value indicating whether there is any handler attached to the named event. yii\base\Component
hasMany() Declares a has-many relation. yii\db\BaseActiveRecord
hasMethod() Returns a value indicating whether a method is defined. yii\base\Component
hasOne() Declares a has-one relation. yii\db\BaseActiveRecord
hasProperty() Returns a value indicating whether a property is defined for this component. yii\base\Component
init() Initializes the object. yii\db\BaseActiveRecord
insert() Inserts a row into the associated database table using the attribute values of this record. yii\db\ActiveRecord
instantiate() Creates an active record instance. yii\db\BaseActiveRecord
isAttributeActive() Returns a value indicating whether the attribute is active in the current scenario. yii\base\Model
isAttributeChanged() Returns a value indicating whether the named attribute has been changed. yii\db\BaseActiveRecord
isAttributeRequired() Returns a value indicating whether the attribute is required. yii\base\Model
isAttributeSafe() Returns a value indicating whether the attribute is safe for massive assignments. yii\base\Model
isPrimaryKey() Returns a value indicating whether the given set of attributes represents the primary key for this model yii\db\BaseActiveRecord
isRelationPopulated() Check whether the named relation has been populated with records. yii\db\BaseActiveRecord
isTransactional() Returns a value indicating whether the specified operation is transactional in the current $scenario. yii\db\ActiveRecord
issetAttribute() Returns if a model attribute is set. spinitron\dynamicAr\DynamicActiveRecord
link() Establishes the relationship between two models. yii\db\BaseActiveRecord
load() Populates the model with the data from end user. yii\base\Model
loadDefaultValues() Loads default values from database table schema yii\db\ActiveRecord
loadMultiple() Populates a set of models with the data from end user. yii\base\Model
markAttributeDirty() Marks an attribute dirty. yii\db\BaseActiveRecord
off() Detaches an existing event handler from this component. yii\base\Component
offsetExists() Returns whether there is an element at the specified offset. yii\base\Model
offsetGet() Returns the element at the specified offset. yii\base\Model
offsetSet() Sets the element at the specified offset. yii\base\Model
offsetUnset() Sets the element value at the specified offset to null. yii\base\Model
on() Attaches an event handler to an event. yii\base\Component
onUnsafeAttribute() This method is invoked when an unsafe attribute is being massively assigned. yii\base\Model
optimisticLock() Returns the name of the column that stores the lock version for implementing optimistic locking. yii\db\BaseActiveRecord
placeholder() Returns a PDO parameter placeholder string, incrementing the placeholder counter. spinitron\dynamicAr\DynamicActiveRecord
populateRecord() spinitron\dynamicAr\DynamicActiveRecord
populateRelation() Populates the named relation with the related records. yii\db\BaseActiveRecord
primaryKey() Returns the primary key name(s) for this AR class. yii\db\ActiveRecord
refresh() Repopulates this active record with the latest data. spinitron\dynamicAr\DynamicActiveRecord
rules() Returns the validation rules for attributes. yii\base\Model
safeAttributes() Returns the attribute names that are safe to be massively assigned in the current scenario. yii\base\Model
save() Saves the current record. yii\db\BaseActiveRecord
scenarios() Returns a list of scenarios and the corresponding active attributes. yii\base\Model
setAttribute() Sets a model attribute. spinitron\dynamicAr\DynamicActiveRecord
setAttributes() Sets the attribute values in a massive way. yii\base\Model
setIsNewRecord() Sets the value indicating whether the record is new. yii\db\BaseActiveRecord
setOldAttribute() Sets the old value of the named attribute. yii\db\BaseActiveRecord
setOldAttributes() Sets the old attribute values. yii\db\BaseActiveRecord
setScenario() Sets the scenario for the model. yii\base\Model
tableName() Declares the name of the database table associated with this AR class. yii\db\ActiveRecord
toArray() Converts the model into an array. yii\base\ArrayableTrait
transactions() Declares which DB operations should be performed within a transaction in different scenarios. yii\db\ActiveRecord
trigger() Triggers an event. yii\base\Component
unlink() Destroys the relationship between two models. yii\db\BaseActiveRecord
unlinkAll() Destroys the relationship in current model. yii\db\BaseActiveRecord
unsetAttribute() Unset a model attribute. spinitron\dynamicAr\DynamicActiveRecord
update() Saves the changes to this active record into the associated database table. yii\db\ActiveRecord
updateAll() Updates the whole table using the provided attribute values and conditions. yii\db\ActiveRecord
updateAllCounters() Updates the whole table using the provided counter changes and conditions. yii\db\ActiveRecord
updateAttributes() Updates the specified attributes. yii\db\BaseActiveRecord
updateCounters() Updates one or several counter columns for the current AR object. yii\db\BaseActiveRecord
validate() Performs the data validation. yii\base\Model
validateMultiple() Validates multiple models. yii\base\Model

Protected Methods

Hide inherited methods

MethodDescriptionDefined By
decodeArrayForMaria() Decodes any data URI strings in an array. spinitron\dynamicAr\DynamicActiveRecord
deleteInternal() Deletes an ActiveRecord without considering transaction. yii\db\ActiveRecord
dotKeyValues() Convert a nested array to a map of dot-notation keys to values. spinitron\dynamicAr\DynamicActiveRecord
dynColSqlMaria() Creates the SQL and parameter bindings for setting dynamic attributes in a DB record as Dynamic Columns in Maria. spinitron\dynamicAr\DynamicActiveRecord
encodeArrayForMaria() Encodes as data URIs any "binary" strings in an array. spinitron\dynamicAr\DynamicActiveRecord
findByCondition() Finds ActiveRecord instance(s) by the given condition. yii\db\ActiveRecord
insertInternal() Inserts an ActiveRecord into DB without considering transaction. yii\db\ActiveRecord
resolveFields() Determines which fields can be returned by toArray(). yii\base\ArrayableTrait
updateInternal() yii\db\BaseActiveRecord
walk() Replacement for PHP's array walk and map builtins. spinitron\dynamicAr\DynamicActiveRecord

Events

Hide inherited events

EventTypeDescriptionDefined By
EVENT_AFTER_DELETE \yii\db\Event An event that is triggered after a record is deleted. yii\db\BaseActiveRecord
EVENT_AFTER_FIND \yii\db\Event An event that is triggered after the record is created and populated with query result. yii\db\BaseActiveRecord
EVENT_AFTER_INSERT \yii\db\Event An event that is triggered after a record is inserted. yii\db\BaseActiveRecord
EVENT_AFTER_UPDATE \yii\db\Event An event that is triggered after a record is updated. yii\db\BaseActiveRecord
EVENT_AFTER_VALIDATE \yii\base\Event An event raised at the end of validate() yii\base\Model
EVENT_BEFORE_DELETE \yii\base\ModelEvent An event that is triggered before deleting a record. yii\db\BaseActiveRecord
EVENT_BEFORE_INSERT \yii\base\ModelEvent An event that is triggered before inserting a record. yii\db\BaseActiveRecord
EVENT_BEFORE_UPDATE \yii\base\ModelEvent An event that is triggered before updating a record. yii\db\BaseActiveRecord
EVENT_BEFORE_VALIDATE \yii\base\ModelEvent An event raised at the beginning of validate(). yii\base\Model
EVENT_INIT \yii\db\Event An event that is triggered when the record is initialized via init(). yii\db\BaseActiveRecord

Constants

Hide inherited constants

ConstantValueDescriptionDefined By
DATA_URI_PREFIX 'data:application/octet-stream;base64,' Prefix for base64 encoded dynamic attribute values spinitron\dynamicAr\DynamicActiveRecord
OP_ALL 7 All three operations: insert, update, delete. This is a shortcut of the expression: OP_INSERT | OP_UPDATE | OP_DELETE. yii\db\ActiveRecord
OP_DELETE 4 The delete operation. This is mainly used when overriding transactions() to specify which operations are transactional. yii\db\ActiveRecord
OP_INSERT 1 The insert operation. This is mainly used when overriding transactions() to specify which operations are transactional. yii\db\ActiveRecord
OP_UPDATE 2 The update operation. This is mainly used when overriding transactions() to specify which operations are transactional. yii\db\ActiveRecord
PARAM_PREFIX ':dqp' Prefix of PDO placeholders for Dynamic Column names and values spinitron\dynamicAr\DynamicActiveRecord
SCENARIO_DEFAULT 'default' The name of the default scenario. yii\base\Model

Property Details

$placeholderCounter protected static property

Counter of PDO placeholders used in a query.

protected static integer $placeholderCounter null

Method Details

__get() public method

PHP getter magic method.

This method is overridden so that attributes and related objects can be accessed like properties.

public mixed __get ( $name )
$name string

Property name

return mixed

Property value

throws \yii\base\InvalidParamException

if relation name is wrong

__isset() public method

Checks if a property value is null.

This method overrides the parent implementation by checking if the named attribute is null or not.

public boolean __isset ( $name )
$name string

The property name or the event name

return boolean

Whether the property value is null

__set() public method

PHP setter magic method.

This method is overridden so that AR attributes can be accessed like properties.

public void __set ( $name, $value )
$name string

Property name

$value mixed

Property value

__unset() public method

Sets a component property to be null.

This method overrides the parent implementation by clearing the specified attribute value.

public void __unset ( $name )
$name string

The property name or the event name

beforeSave() public method

public boolean beforeSave ( $insert )
$insert boolean
throws \yii\base\Exception
columnExpression() public static method

Generate an SQL expression referring to the given dynamic column.

public static string columnExpression ( $name, $type 'char' )
$name string

Attribute name

$type string

SQL datatype type

return string

A Maria COLUMN_GET expression

decodeArrayForMaria() protected static method

Decodes any data URI strings in an array.

protected static void decodeArrayForMaria ( &$array )
$array array

The array

decodeForMaria() public static method

Decode strings encoded as data URIs.

public static string decodeForMaria ( $value )
$value string

The data URI to decode

return string

The decoded value

dotAttributeNames() public method

Return a list of all model attribute names recursing structured dynamic attributes.

public array dotAttributeNames ( )
return array

An array of all attribute names in dotted notation

throws \yii\base\Exception
dotAttributes() public method

Return a list of all attribute values with keys in dotted notation.

public array dotAttributes ( )
return array

Array of attribute values with attribute names as array keys in dotted notation.

throws \yii\base\Exception
dotKeyValues() protected static method

Convert a nested array to a map of dot-notation keys to values.

protected static array dotKeyValues ( $prefix, $array )
$prefix string

Prefix returned array keys with this string

$array array

Nested array of attributeName => value pairs

return array

Map of keys in dotted notation to corresponding values

dynColDecode() public static method

Decode a serialized blob of dynamic attributes.

At present the only supported input format is JSON returned from Maria. It may work also for PostgreSQL.

public static array dynColDecode ( $encoded )
$encoded string

Serialized array of attributes in DB-specific form

return array

Dynamic attributes in name => value pairs (possibly nested)

dynColExpression() public static method

Creates a dynamic column SQL expression representing the given attributes.

public static null|\yii\db\Expression dynColExpression ( $attrs )
$attrs array

The dynamic attributes, which may be nested

dynColSqlMaria() protected static method

Creates the SQL and parameter bindings for setting dynamic attributes in a DB record as Dynamic Columns in Maria.

protected static string dynColSqlMaria ( array $attrs, &$params )
$attrs array

The dynamic attributes, which may be nested

$params array

Expression parameters for binding, passed by reference

return string

SQL for a DB Expression

throws \yii\base\Exception
dynamicColumn() public static method

Specifies the name of the table column containing dynamic attributes.

public static string dynamicColumn ( )
return string

Name of the table column containing dynamic column data

throws \yii\base\Exception

if not overriden by descendent class.

encodeArrayForMaria() protected static method

Encodes as data URIs any "binary" strings in an array.

protected static void encodeArrayForMaria ( &$array )
$array array

The array

encodeForMaria() public static method

Encode as data URIs strings that JSON cannot express.

public static string encodeForMaria ( $value )
$value mixed

A value to encode

return string

The encoded data URI

fields() public method

Returns the list of fields that should be returned by default by toArray() when no specific fields are specified.

A field is a named element in the returned array by toArray().

This method should return an array of field names or field definitions. If the former, the field name will be treated as an object property name whose value will be used as the field value. If the latter, the array key should be the field name while the array value should be the corresponding field definition which can be either an object property name or a PHP callable returning the corresponding field value. The signature of the callable should be:

function ($model, $field) {
    // return field value
}

For example, the following code declares four fields:

  • email: the field name is the same as the property name email;
  • firstName and lastName: the field names are firstName and lastName, and their values are obtained from the first_name and last_name properties;
  • fullName: the field name is fullName. Its value is obtained by concatenating first_name and last_name.
return [
    'email',
    'firstName' => 'first_name',
    'lastName' => 'last_name',
    'fullName' => function () {
        return $this->first_name . ' ' . $this->last_name;
    },
];

In this method, you may also want to return different lists of fields based on some context information. For example, depending on the privilege of the current application user, you may return different sets of visible fields or filter out some fields.

The default implementation of this method returns the public object member variables indexed by themselves.

public array fields ( )
return array

The list of field names or field definitions.

find() public static method

Returns a query object for the model/class.

public static spinitron\dynamicAr\DynamicActiveQuery find ( )
getAttribute() public method

Returns a model attribute value.

public mixed|null getAttribute ( $name )
$name string

Attribute name, use dotted notation for structured attributes.

return mixed|null

The attribute value or null if the attribute does not exist

issetAttribute() public method

Returns if a model attribute is set.

public boolean issetAttribute ( $name )
$name string

Attribute name, use dotted notation for structured attributes.

return boolean

True if the attribute is set

placeholder() public static method

Returns a PDO parameter placeholder string, incrementing the placeholder counter.

public static string placeholder ( )
return string

The placeholder string

populateRecord() public static method

public static void populateRecord ( $record, $row )
$record spinitron\dynamicAr\DynamicActiveRecord
$row array
throws \yii\base\Exception
refresh() public method

Repopulates this active record with the latest data.

public boolean refresh ( )
return boolean

Whether the row still exists in the database. If true, the latest data will be populated to this active record. Otherwise, this record will remain unchanged.

setAttribute() public method

Sets a model attribute.

public void setAttribute ( $name, $value )
$name string

Attribute name, use dotted notation for structured attributes.

$value mixed

The attribute value. A value of null effectively unsets the attribute.

unsetAttribute() public method

Unset a model attribute.

public void unsetAttribute ( $name )
$name string

Attribute name, use dotted notation for structured attributes.

walk() protected static method

Replacement for PHP's array walk and map builtins.

protected static void walk ( &$array, $method )
$array array

An array to walk, which may be nested

$method callable

A method to map on the array